/*
 * @Author       : 吴豪
 * @Date         : 2021-12-4 15:56:22
 * @FilePath     : \book-manage-front\src\pages\userManage\index.tsx
 * @Description  : 用户管理页面
 */

import { PageContainer } from '@ant-design/pro-layout';
import React, { useRef, useState } from 'react';
import { Button, message, Popconfirm, Space, Switch, Tooltip } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  getUserList,
  enableUser,
  getUserStateList,
  deleteUser,
  downloadEnclosure,
} from '@/services/user';
import type { ParamsType } from '@ant-design/pro-provider';
import CreateUser from './usersComponents/CreateUser';
import EditUser from './usersComponents/EditUser';
import styles from './index.less';
import type { UserList } from '@/dataType';

/**
 * 用户管理界面，引用组件实现功能
 * @returns
 */
function UserManage() {
  const actionRef = useRef<ActionType>();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalVisibleEdit, setIsModalVisibleEdit] = useState(false);
  const [userAid, setUserAid] = useState(undefined);

  /**
   * 新增模态框的控制
   */
  const isShowModal = (show: boolean | ((prevState: boolean) => boolean)) => {
    setIsModalVisible(show);
  };

  /**
   * 修改模态框的控制
   */
  const isShowModalEdit = (show: boolean | ((prevState: boolean) => boolean), aid: any) => {
    setUserAid(aid);
    setIsModalVisibleEdit(show);
  };

  /**
   * 点击修改时获取用户列表数据
   * @param params
   * @returns
   */
  const getUsersData = async (
    params: ParamsType & {
      pageSize?: number | undefined;
      current?: number | undefined;
      keyword?: string | undefined;
    },
  ) => {
    const param = {
      searchKey: params.searchKey,
      stateId: params.stateId,
      page: params.current!,
      pageSize: params.pageSize!,
    };
    const response = await getUserList(param);
    return {
      data: response.list!,
      success: true,
      total: response.rowsNum!,
    };
  };

  /**
   * 删除用户按钮确认提示
   * @param params
   */
  const confirm = async (aid: number) => {
    const params = {
      aid: aid,
    };
    const response = await deleteUser(params);
    if (response) {
      message.success('删除成功！');
      actionRef.current?.reload();
    }
  };

  function cancel() {
    message.error('取消删除！');
  }

  /**
   * 表格的设计
   */
  const columns: ProColumns<UserList>[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '员工姓名',
      dataIndex: 'searchKey',
      copyable: true,
      ellipsis: true,
      hideInTable: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: '密码',
      dataIndex: 'password',
      hideInSearch: true,
    },
    {
      title: '是否启用',
      dataIndex: 'stateId',
      key: 'stateId',
      hideInSearch: true,
      render: (_, record) => (
        /**
         * 调用接口实现用户的启用和禁用
         */
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.stateId ? true : false}
          onChange={async () => {
            await enableUser(record.aid);
          }}
        />
      ),
    },
    {
      title: '状态',
      dataIndex: 'stateId',
      filters: true,
      onFilter: true,
      valueType: 'select',
      hideInTable: true,
      /**
       * 调用接口，获取并渲染用户状态列表
       * @returns
       */
      request: async () => {
        const data = await getUserStateList();
        return data.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      },
    },
    {
      title: '附件',
      dataIndex: 'enclosureName',
      hideInSearch: true,
      /**
       * 调用接口，实现对附件的下载
       * @param record
       * @returns
       */
      render: (_, record) => {
        return record.enclosureId ? (
          <Tooltip title="点击下载">
            <Button
              type="link"
              onClick={async () => {
                await downloadEnclosure({ enclosureId: record.enclosureId! });
              }}
            >
              {record.enclosureName}
            </Button>
          </Tooltip>
        ) : (
          <Tooltip title="点击下载">
            <Button type="link" onClick={() => message.info('该用户无附件')}>
              下载附件
            </Button>
          </Tooltip>
        );
      },
    },
    {
      title: '新增日期',
      key: 'showTime',
      dataIndex: 'createDate',
      valueType: 'date',
      hideInSearch: true,
    },
    {
      title: '操作',
      hideInSearch: true,
      /**
       * 用户的修改与删除
       * @param record
       * @returns
       */
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            className={styles.button}
            onClick={() => {
              isShowModalEdit(true, record.aid);
            }}
          >
            修改
          </Button>
          <Popconfirm
            placement="topRight"
            title="你确认要删除该项数据吗??"
            onConfirm={() => confirm(record.aid)}
            onCancel={cancel}
            okText="确认"
            cancelText="取消"
          >
            <Button type="link" className={styles.button}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '用户管理',
        ghost: true,
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '组织构架',
            },
            {
              path: '',
              breadcrumbName: '用户管理',
            },
          ],
        },
      }}
    >
      <ProTable<UserList>
        columns={columns}
        actionRef={actionRef}
        request={(params) => getUsersData(params)}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="aid"
        search={{
          span: 6,
        }}
        options={{
          density: false,
          setting: false,
          fullScreen: true,
        }}
        pagination={{
          pageSize: 10,
          size: 'default',
          showTotal: undefined,
        }}
        dateFormatter="string"
        headerTitle="用户列表"
        toolBarRender={() => [
          <Button
            key="button"
            type="primary"
            onClick={() => {
              isShowModal(true);
            }}
          >
            新增
          </Button>,
        ]}
      />

      {/* 引用新增用户组件 */}
      <CreateUser isModalVisible={isModalVisible} isShowModal={isShowModal} actionRef={actionRef} />

      {/* 引用修改用户组件 */}
      <EditUser
        isModalVisible={isModalVisibleEdit}
        isShowModal={isShowModalEdit}
        actionRef={actionRef}
        userAid={userAid}
      />
    </PageContainer>
  );
}

export default UserManage;
